package com.ymttest.database.mongo;

import static com.ymttest.database.mongo.config.SchemaField.ORDER;

import java.util.List;

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOptions;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.mongodb.WriteResult;
import com.ymatou.iapi.synctrade.parameter.mongo.Order;
import com.ymttest.database.mongo.config.MongoOrderConfig;
import com.ymttest.database.mongo.config.OrderField;

public class OrderQueryWapper {

	private MongoTemplate mongoOrderTemplate;

	public OrderQueryWapper() {
		try {

			mongoOrderTemplate = new MongoOrderConfig().mongoTemplate();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据订单号获取订单详细信息
	 *
	 * @param orderId
	 * @return
	 */
	public Order findById(long orderId) {
		return mongoOrderTemplate.findById(orderId, Order.class, ORDER);
	}

	public List<Order> findByIds(List<Long> orderIdList) {
		return mongoOrderTemplate.find(
				Query.query(Criteria.where(OrderField.ID).in(orderIdList)),
				Order.class, ORDER);
	}

	public List<Order> queryByCriteria(Criteria criteria) {
		return mongoOrderTemplate.find(Query.query(criteria), Order.class,
				ORDER);
	}

	public List<Order> find(Query query) {
		return mongoOrderTemplate.find(query, Order.class, ORDER);
	}

	public Order findOneByCriteria(Criteria criteria) {
		return mongoOrderTemplate.findOne(Query.query(criteria), Order.class,
				ORDER);
	}

	public Order findOneByQuery(Query query) {
		return mongoOrderTemplate.findOne(query, Order.class, ORDER);
	}

	public <T> List<T> aggregation(Aggregation aggregation, Class<T> outputType) {
		aggregation = aggregation.withOptions(new AggregationOptions.Builder()
				.allowDiskUse(true).build());
		return mongoOrderTemplate.aggregate(aggregation, ORDER, outputType)
				.getMappedResults();
	}
	
	/**
	 * 根据订单号修改加密地址
	 *
	 * @param orderId
	 * @return
	 */
	public WriteResult updateUAddress(long orderId, String address) {
		
		Query query = new Query();
		
		query.addCriteria(Criteria.where(OrderField.ID).is(orderId));
		
		return mongoOrderTemplate.updateFirst(query,
				new Update().set(OrderField.UADDRESS, address), Order.class, ORDER);
	}

	public static void main(String[] args) {

//		List<Order> orderList = new OrderQueryWapper().findByUserIdAndSellerId(20238699, 24635724);
//		
//		int actualCount = orderList.stream()
//				.filter(OrderPo -> OrderPo.getPaidTime() != null)
//				.collect(Collectors.toList()).size();
//		
//		System.out.println(actualCount);
		
		OrderQueryWapper wrapper = new OrderQueryWapper();
		
		System.out.println(wrapper.findOneByQuery(
				Query.query(Criteria.where(OrderField.ID).is(10374968699L)))
				.getUaddress());
	}
}
